<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>三级联动</title>
    <script src="./city_code.js"></script>
    <style>
        body {
            position: relative;
        }

        body>div {
            float: left;
            margin: 0 30px;
        }

        .box {
            position: absolute;
            left: 0;
            display: none;
            width: 100%;
        }
    </style>
</head>

<body><div>
        <span class="text">省</span>
        <div class="box"></div>
    </div>
    <div>
        <span class="text">市</span>
        <div class="box"></div>
    </div>
    <div>
        <span class="text">县</span>
        <div class="box"></div>
    </div>
</body>

</html>
<script>
    // 获取所有的box
    const box = document.querySelectorAll('.box');
    const text = document.querySelectorAll('.text');
    const divs = document.querySelectorAll('body>div');

    divs.forEach(function (div) {
        // 鼠标移入，显示待选项
        div.onmouseenter = function (e) {
            e.target.querySelector('.box').style.display = 'block';
        }
        div.onmouseleave = function (e) {
            e.target.querySelector('.box').style.display = 'none';
        }
    })

    // 在省的box中添加待选项
    createBtn(city_code, box[0], shengClick);
    function shengClick(event) {
        // 先清除子元素
        box[1].innerHTML = '';
        box[2].innerHTML = '';
        text[0].innerText = event.target.innerText;
        // 创建市选项
        createBtn(event.target.city, box[1], shiClick);
    }
    function shiClick(e) {
        box[2].innerHTML = '';
        // 创建县选项
        createBtn(event.target.city, box[2], xianClick);
    }
    function xianClick(e) {

    }

    /**
     * 在box元素中创建按钮
     * type 只能是 'area'或'city'
     */
    function createBtn(data, dom, fn, type) {
        // 在省的box中添加待选项
        data.forEach(function (val) {
            // 创建button标签
            const btn = document.createElement('button');
            // 添加到页面
            dom.append(btn);
            // 设置按钮文本
            btn.innerText = val.name;
            // 绑定点击事件
            btn.onclick = fn;
            // 存储城市信息
            // btn.city = val[type];    // 动态取值方案

            // 如果city为undefined，则取val.area，如果val.area也为undefined，则取空数组
            btn.city = val.city || val.area || [];

        });
    }
</script>